package com.accenture.portal.controller.book;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.ParseException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.accenture.portal.controller.UserController;
import com.accenture.portal.model.book.BookBorrow;
import com.accenture.portal.model.book.BookDetail;
import com.accenture.portal.model.questionnaire.Question;
import com.accenture.portal.model.questionnaire.Questionnaire;
import com.accenture.portal.service.book.BookService;
import com.accenture.portal.util.LogManagerUtil;

@Controller
public class BookController
{
	
	private static Logger business = Logger.getLogger(UserController.class.getName());
	
	@Autowired
	private BookService bs;
	
	/**
	 * 前台查找图书
	 * @author chuyan.qi
	 * @param request
	 * @param response
	 * @return
	 * @throws java.text.ParseException 
	 */
	@RequestMapping(value = "searchBooks.action", method = RequestMethod.POST)
	public ModelAndView searchBooks (@RequestParam("borrowReaderid") Integer borrowReaderid,@RequestParam("keyword") String keywords,HttpServletRequest request, HttpServletResponse response, Model model) throws java.text.ParseException {
		String keyword="%"+keywords+"%";
		List<BookDetail> bookList = bs.searchBookByKeyword(keyword);
		model.addAttribute("allBookList", bookList);
		request.getSession().setAttribute("keyword", keywords);
		
		List<BookBorrow> borrowBook = bs.listBookByUserId(borrowReaderid);
		for (BookBorrow bookBorrow : borrowBook)
		{ 
		     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		     String dateStr2 = format.format(new Date());
		     int mustReturn = bookBorrow.getMustReturn();
		     try 
		     {
		         Date date2 = format.parse(dateStr2);
		         Date date = bookBorrow.getBorrowTime();
		         int readedDay = differentDaysByMillisecond(date,date2);
		         int leftDay = mustReturn - readedDay;
		         bookBorrow.setLeftDay(leftDay);
		     } catch (ParseException e) {
		         e.printStackTrace();
		     }
		}
		model.addAttribute("userBorrowBook",borrowBook);
		return new ModelAndView ("book/bookFrontend");
	}
	
	/**
	 * 显示图书列表前台页面
	 * @author chuyan.qi
	 * @param request
	 * @param response
	 * @return
	 * @throws java.text.ParseException 
	 */
	@RequestMapping("showBooks.action")
	public ModelAndView showBooks (@RequestParam("borrowReaderid") Integer borrowReaderid,HttpServletRequest request, HttpServletResponse response, Model model) throws java.text.ParseException {
		List<BookDetail> bookList = bs.listAllBooks();
		model.addAttribute("allBookList", bookList);
		
		List<BookBorrow> borrowBook = bs.listBookByUserId(borrowReaderid);
		for (BookBorrow bookBorrow : borrowBook)
		{ 
		     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		     String dateStr2 = format.format(new Date());
		     int mustReturn = bookBorrow.getMustReturn();
		     try 
		     {
		         Date date2 = format.parse(dateStr2);
		         Date date = bookBorrow.getBorrowTime();
		         int readedDay = differentDaysByMillisecond(date,date2);
		         int leftDay = mustReturn - readedDay;
		         bookBorrow.setLeftDay(leftDay);
		     } catch (ParseException e) {
		         e.printStackTrace();
		     }
		}
		model.addAttribute("userBorrowBook",borrowBook);
		return new ModelAndView ("book/bookFrontend");
	}
	
	/**
	 * 时间差
	 * @author chuyan.qi
	 * @return
	 */
	public static int differentDaysByMillisecond(Date date1, Date date2)
	{
		int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
		return days;
	}
	
	/**
	 * 显示已借出图书结束信息
	 * @author chuyan.qi
	 * @param request
	 * @param response
	 * @return
	 * @throws java.text.ParseException 
	 * @throws IOException 
	 */
	@RequestMapping("showBorrowByBook.action")
	public void showBorrowByBook (@RequestParam("borrowBookid") Integer borrowBookid,HttpServletRequest request, HttpServletResponse response, Model model) throws java.text.ParseException, IOException {
		List<BookBorrow> borrowBook = bs.showBorrowByBook(borrowBookid);
		for (BookBorrow bookBorrow : borrowBook)
		{ 
		     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		     String dateStr2 = format.format(new Date());
		     int mustReturn = bookBorrow.getMustReturn();
		     try 
		     {
		         Date date2 = format.parse(dateStr2);
		         Date date = bookBorrow.getBorrowTime();
		         int readedDay = differentDaysByMillisecond(date,date2);
		         int leftDay = mustReturn - readedDay;
		         bookBorrow.setLeftDay(leftDay);
		     } catch (ParseException e) {
		         e.printStackTrace();
		     }
		}
		//model.addAttribute("bookUserBorrowList",borrowBook);
		String text = JSONArray.fromObject(borrowBook).toString();
		PrintWriter out = response.getWriter();
		out.write(text);
	}
	
	/**
	 * 图书管理后台分页
	 * 
	 * @author chuyan.qi
	 * @param number
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "searchBookByPage.action")
	public String searchBookByPage(@RequestParam("number") int number,
			HttpServletRequest request, Model model)
	{
		// 设置每页显示多少行
		int page = 7;

		// 获取当前页
		if (number < 1)
		{
			number = 1;
		}

		// 总条数
		int total = bs.totalBookCount();
		// 总页数
		int count = total / page;
		if (total % page != 0)
		{
			count++;
		}
		if (count == 0)
		{
			count = 1;
		}
		if (number > count)
		{
			number = count;
		}

		List<BookDetail> searchBookList = bs.searchBookByPage((number - 1) * page,
				page);

		request.getSession().setAttribute("number", number);
		model.addAttribute("searchBookList", searchBookList);
		request.getSession().setAttribute("count", count);

		return "book/bookBackend";
	}
	
	/**后台管理搜索功能
	 * @param number
	 * @param searchBookType
	 * @param searchWord
	 * @param bookState
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "searchBook.action")
	public String searchBook(
			@RequestParam("number") Integer number,//当前页码
			@RequestParam("searchBookType") Integer searchBookType,  //搜索类型
			@RequestParam("searchWord") String searchWord1,//输入的搜索关键字
			@RequestParam("bookState") Integer bookState,//问卷状态
			HttpServletRequest request, Model model) {
		String searchWord="%"+searchWord1+"%";
		Integer page = 7;//每页显示条数
		Integer total=0;//总条数
		Integer count=0;//显示的总页数
		List<BookDetail> searchBookList = new ArrayList<BookDetail>();
		//筛选条件
		switch (searchBookType) {
		case 0:  //获取全部问卷
			total = bs.totalBookCount();//总条数
			count=getCount(page,total, count);
			number=getNumber(number, count);
			searchBookList = bs.searchBookByPage((number - 1)* page, page);//取一页的数据
		    break;
		case 1:  //按书名搜索
			total = bs.searchBookByNameCount(searchWord);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			searchBookList = bs.searchBookByName(searchWord, (number - 1)* page,page);
		    break;
		case 2:  //按作者搜索
			total =  bs.searchBookByAuthorCount(searchWord);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			searchBookList = bs.searchBookByAuthor(searchWord, (number - 1)* page,page);
		    break;
		case 3:  //按出版社搜索
			total =  bs.searchBookByPressCount(searchWord);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			searchBookList = bs.searchBookByPress(searchWord, (number - 1)* page,page);
		    break;
		case 4:  //按图书状态（在库/已借出）搜索
			total =  bs.searchBookByStatusCount(bookState);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			searchBookList = bs.searchBookByStatus(bookState, (number - 1)* page,page);
		    break;
		default:
		    System.out.println("searchType is not right！！");
		}

		model.addAttribute("searchBookList", searchBookList);
		request.getSession().setAttribute("count", count);
		request.getSession().setAttribute("number", number);
		request.getSession().setAttribute("searchBookType", searchBookType);//保存搜索类型，
		request.getSession().setAttribute("searchWord", searchWord1);
		request.getSession().setAttribute("bookState", bookState);
		return "book/bookBackend";
	}
	
	/**计算number的工具方法
	 * @param number
	 * @param count
	 * @return
	 */
	public Integer getNumber(Integer number,Integer count){
		if (number < 1) {//当前最小页数限制
			number = 1;
		} else if (number > count) {
			number = count;//当前最大页数限制
		}
		return number;
	}
	
	/**计算count的工具方法
	 * @param page
	 * @param total
	 * @param count
	 * @return
	 */
	public Integer getCount(Integer page,Integer total,Integer count){
		count = total / page;
		if (total % page != 0) {  
			count++;              //总页数
		}
		
		if(count==0){ 
			count=1;//数据库没有数据时显示在总共1页
		}
		return count;
	}
	
	/**融合搜索
	 * @param bookName
	 * @param bookAuthor
	 * @param bookPress
	 * @param bookState
	 * @param number
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "fusionSearchBook.action")
	public String fusionSearchBook(
			@RequestParam("bookName") String bookNameTemp,
			@RequestParam("bookAuthor") String bookAuthorTemp,
			@RequestParam("bookPress") String bookPressTemp,
			@RequestParam("bookState") String bookStateTemp,
			@RequestParam("number") Integer number,
			HttpServletRequest request, Model model) {
		String bookName="%"+bookNameTemp+"%";
		String bookAuthor="%"+bookAuthorTemp+"%";
		String bookPress="%"+bookPressTemp+"%";
		String bookState;
		if(bookStateTemp.equals("2")){
			bookState="%%";
		}
		else{
			bookState="%"+bookStateTemp+"%";
		}
		
		Integer page = 7;//每页显示条数
		Integer total=0;//总条数
		Integer count=0;//总页数
		total = bs.fusionSearchBookCount(bookName, bookAuthor, bookPress, bookState);//总条数
		count=getCount(page,total, count);
		number=getNumber(number, count);
		List<BookDetail> searchBookList = bs.fusionSearchBook(bookName, bookAuthor, bookPress, bookState, (number - 1)* page, page);//取一页的数据
		model.addAttribute("searchBookList", searchBookList);
		request.getSession().setAttribute("count", count);
		request.getSession().setAttribute("number", number);
		request.getSession().setAttribute("bookName", bookNameTemp);
		request.getSession().setAttribute("bookAuthor", bookAuthorTemp);
		request.getSession().setAttribute("bookPress", bookPressTemp);
		request.getSession().setAttribute("bookState", bookStateTemp);
		return "book/bookBackend";
	}

	/**
	 * 增加图书
	 * 
	 * @author chuyan.qi
	 * @param record
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("showAddBook.action")
	public ModelAndView showAddBook(HttpServletRequest request,
			HttpServletResponse response)
	{
		return new ModelAndView("book/addBook");
	}

	@RequestMapping(value = "saveBook.action", method = RequestMethod.POST)
	public String saveBook(@RequestParam("addBookName") String addBookName,
			@RequestParam("addBookImage") CommonsMultipartFile addfile,
			@RequestParam("addBookAuthor") String addBookAuthor, 
			@RequestParam("addBookPress") String addBookPress, 
			@RequestParam("addbookPublishdate") String bookPublishdateString,
			@RequestParam("addBookIsbn") String addBookIsbn,
			HttpServletRequest request, ModelMap model) throws java.text.ParseException{
		
		BookDetail bookDetail = new BookDetail();
		
		String fileName = addfile.getOriginalFilename();
		
		if (!fileName.endsWith(".jpg")) {
			return "book/failBook";
		}
		
		ServletContext sc = request.getSession().getServletContext();

		String path = sc.getRealPath("/img") + "/"; 
		System.out.println(path);
		File f = new File(path);
		if (!f.exists())
			f.mkdirs();//文件不存在建新文件
		if (!addfile.isEmpty()) {
			try {
				FileOutputStream fos = new FileOutputStream(path + fileName);
				InputStream in = addfile.getInputStream();
				int b = 0;
				while ((b = in.read()) != -1) {
					fos.write(b);
				}
				fos.close();
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		bookDetail.setBookName(addBookName);
		String url = path + fileName;
		url=getNewURL(url);
		bookDetail.setBookImage(url);
		bookDetail.setBookAuthor(addBookAuthor);
		bookDetail.setBookPress(addBookPress);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
		Date bookPublishdate = sdf.parse(bookPublishdateString);//日期转为Date型
		bookDetail.setBookPublishdate(bookPublishdate);
		bookDetail.setBookIsbn(addBookIsbn);
		bs.saveBook(bookDetail);
		
		LogManagerUtil.recordBusinessLog("Alice", "book", "add", "success","add successful");
		business.debug("success");
		
		int number = (int) request.getSession().getAttribute("number");//获取当前页
		return "redirect:searchBookByPage.action?number=" + number;//返回并刷新当前页
	}
	
	/**
	 * image路径处理
	 * @author chuyan.qi
	 */
	private String getNewURL(String url)
	{
		int index=url.lastIndexOf("\\");
		String newString=url.substring(index+1);
		return newString;
	}

	/**  
     * 编辑图书
     * @author chuyan.qi
     * @param bookId  
     * @param request  
     * @return  
     */
	@RequestMapping(value = "showEditBook.action", method = RequestMethod.GET)
	public void showEditBook(@RequestParam("bookId") Integer bookId,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		BookDetail book = bs.findBookById(bookId);
		request.getSession().setAttribute("bookId", bookId);
		Date bookPublishdate = book.getBookPublishdate();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String bookPublishdateLast = sdf.format(bookPublishdate);
        request.getSession().setAttribute("bookPublishdateLast", bookPublishdateLast);
		model.addAttribute("editBookList", book);
		Map<String,Object> mapMulti=new HashMap<String, Object>();//封装为map发送到前台
		mapMulti.put("bookPublishdateLast",bookPublishdateLast);
		mapMulti.put("editBookList", book);
		JSONObject json = JSONObject.fromObject(mapMulti);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "updateBook.action", method = RequestMethod.POST)
	public String updateBook(
			@RequestParam("editBookName") String editBookName,
			@RequestParam("editBookImage") CommonsMultipartFile editfile,
			@RequestParam("editBookImageNull") String editBookImageNull,
			@RequestParam("editBookAuthor") String editBookAuthor,
			@RequestParam("editBookPress") String editBookPress,
			@RequestParam("editBookPublishdate") String bookPublishdateString,
			@RequestParam("editBookIsbn") String editBookIsbn,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws java.text.ParseException
	{
		BookDetail bookDetail = new BookDetail();
		
		String fileName = editfile.getOriginalFilename();
		
		if(fileName == null || fileName.isEmpty()){
			bookDetail.setBookImage(editBookImageNull);
		}else{
		if (!fileName.endsWith(".jpg")) {
			return "book/failBook";
		}
		
		ServletContext sc = request.getSession().getServletContext();

		String path = sc.getRealPath("/img") + "/"; 
		System.out.println(path);
		File f = new File(path);
		if (!f.exists())
			f.mkdirs();//文件不存在建新文件
		if (!editfile.isEmpty()) {
			try {
				FileOutputStream fos = new FileOutputStream(path + fileName);
				InputStream in = editfile.getInputStream();
				int b = 0;
				while ((b = in.read()) != -1) {
					fos.write(b);
				}
				fos.close();
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String url = path + fileName;
		url=getNewURL(url);
		bookDetail.setBookImage(url);
		}
		
		bookDetail.setBookName(editBookName);
		bookDetail.setBookId((Integer)request.getSession().getAttribute("bookId"));
		bookDetail.setBookAuthor(editBookAuthor);
		bookDetail.setBookPress(editBookPress);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
		Date bookPublishdate = sdf.parse(bookPublishdateString);//日期转为Date型
		bookDetail.setBookPublishdate(bookPublishdate);
		bookDetail.setBookIsbn(editBookIsbn);
		bs.updateBook(bookDetail);
		
		LogManagerUtil.recordBusinessLog("Alice", "book", "update", "success","update successful");
		business.debug("success");
		
		int number = (int) request.getSession().getAttribute("number");// 获取当前页
		return "redirect:searchBookByPage.action?number=" + number;// 返回并刷新当前页
	}
	
	/**逻辑删除图书
	 * @param bookId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "deleteBook.action", method = RequestMethod.GET)
	public String deleteBook(@RequestParam("bookId") Integer bookId,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		bs.removeBook(bookId);
		
		LogManagerUtil.recordBusinessLog("Alice", "book", "delete", "success","delete successful");
		business.debug("success");
		
		int number = (int) request.getSession().getAttribute("number");
		return "redirect:searchBookByPage.action?number=" + number;//返回并刷新当前页
	}
	
	/**逻辑删除多本图书
	 * @param bookIdList
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "deleteBookMulti.action", method = RequestMethod.GET)
	public void deleteQuestionnaireMulti(@RequestParam("bookIdList") String bookIdList,
			HttpServletRequest request,HttpServletResponse response, Model model) {
		String bookMulti[] = bookIdList.split(",");//分割出所有问卷id
		for (Integer i = 0; i < bookMulti.length; i++) {
			Integer bookId = Integer.valueOf(bookMulti[i]);
			bs.removeBook(bookId);
		}
	}
	
	/**  
     * 借阅图书
     * @author chuyan.qi
     * @param bookId  
     * @param request  
	 * @return 
     */  
	@RequestMapping(value = "showBorrowBook.action", method = RequestMethod.GET)
	public void showBorrowBook(@RequestParam("bookId") Integer bookId, @RequestParam("borrowReaderid") Integer borrowReaderid,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		int number = bs.getBookCountByUserId(borrowReaderid);
		BookDetail book = bs.findBookById(bookId);
		request.getSession().setAttribute("bookId", bookId);
		model.addAttribute("borrowBook", book);
		
		Map<String,Object> mapMulti=new HashMap<String, Object>();//封装为map发送到前台
		mapMulti.put("borrowNumber",number);
		mapMulti.put("borrowBook", book);
		JSONObject json = JSONObject.fromObject(mapMulti);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "borrowBook.action", method = RequestMethod.POST)
	public String borrowBook(BookBorrow bookBorrow, 
			HttpServletRequest request, HttpServletResponse response,
			Model model)
	{
		bookBorrow.setBorrowTime(new Date());
		bs.borrowBook(bookBorrow);
		Integer borrowBookid = bookBorrow.getBorrowBookid();
		Integer borrowReaderid = bookBorrow.getBorrowReaderid();
		Integer borrowId = bs.findBorrowId(borrowBookid,borrowReaderid);
		bs.updateBorrowState(borrowId);
		
		int userid = bookBorrow.getBorrowReaderid();
		return "redirect:showBooks.action?borrowReaderid=" + userid;
	}
	
	/**  
     * 归还图书
     * @author chuyan.qi
     * @param bookId  
     * @param request  
	 * @return 
     */
	@RequestMapping("showReturnBook.action")
	public String showReturnBook(@RequestParam("borrowId") Integer borrowId,@RequestParam("userid") Integer userid,
			HttpServletRequest request, HttpServletResponse response,Model model)
	{
		BookBorrow book = bs.findBorrowById(borrowId);
		book.setReturnTime(new Date());
		bs.returnBook(book);
		bs.updateReturnState(borrowId);
		
		return "redirect:showBooks.action?borrowReaderid=" + userid;
	}
	
	/**  
     * 查看图书
     * @author chuyan.qi
     * @param bookId  
     * @param request  
	 * @return 
	 * @return 
     */
	@RequestMapping("showBookDetail.action")
	public void showBookDetail(@RequestParam("bookId") int bookId,
			HttpServletRequest request, HttpServletResponse response,Model model)throws Exception
	{
		BookDetail book = bs.findBookById(bookId);
		String text = JSONArray.fromObject(book).toString();
		PrintWriter out = response.getWriter();
		out.write(text);
	}
}
